package qingxin.dao.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import qingxin.dao.NewsTagDAO;
import qingxin.dbc.DatabaseConnection;
import qingxin.vo.Tag;

public class NewsTagDAOImpl implements NewsTagDAO {

	@Override
	public Tag[] getByNewsID(int newsID) throws Exception {
		ArrayList<Tag> tags = new ArrayList<Tag>();
		String sql = "select ntid, nt_nid, tag from news_tag where nt_nid = ?";
		DatabaseConnection dbc = null;
		try{
			dbc = new DatabaseConnection();
			PreparedStatement pstmt = dbc.getConnection().prepareStatement(sql);
			pstmt.setInt(1, newsID);
			
			ResultSet rs = pstmt.executeQuery();
			while(rs.next()){
				Tag tag = new Tag();
				tag.setTagID(rs.getInt(1));
				tag.setNewsID(rs.getInt(2));
				tag.setTag(rs.getString(3));
				tags.add(tag);
			}
		}
		catch(Exception e){
			throw e;
		}
		finally{
			dbc.close();
		}
		return tags.toArray(new Tag[0]);
	}

	@Override
	public void addTag(int newsID, String tag) throws Exception {
		String sql = "insert into news_tag (nt_nid, tag) values (?,?)";
		DatabaseConnection dbc = null;
		try{
			dbc = new DatabaseConnection();
			PreparedStatement pstmt = dbc.getConnection().prepareStatement(sql);
			
			pstmt.setInt(1, newsID);
			pstmt.setString(2, tag);
			
			pstmt.executeUpdate();
		}
		catch(Exception e){
			throw e;
		}
		finally{
			dbc.close();
		}
		
	}

	@Override
	public void deleteTag(int tagID) throws Exception {
		String sql = "delete from news_tag where ntid = ?";
		DatabaseConnection dbc = null;
		try{
			dbc = new DatabaseConnection();
			PreparedStatement pstmt = dbc.getConnection().prepareStatement(sql);
			
			pstmt.setInt(1, tagID);
			
			pstmt.executeUpdate();
		}
		catch(Exception e){
			throw e;
		}
		finally{
			dbc.close();
		}
	}

}
